<template>
	<view class="head_main">
		<!-- 圆形进度条 -->
		<view class="progress-container">
			<canvas ref="healthChart" canvas-id="healthProgressChart" class="health-progress-chart"></canvas>
			<view class="score-container">
				<view class="health-score">
					{{ isConnect ? healthScore : "--" }}
					<view class="no-data-tip" v-if="isConnect && progress<100">
						数据同步中 {{progress}} %
					</view>
				</view>
				<view v-if="!isConnect" class="no-data-tip">暂无数据</view>
			</view>
		</view>
		<!-- 💍名称
    <view class="ring_name">{{ ringName || "-" }}</view>-->
		<!-- 按钮 -->
		<view v-if="!isConnect" class="button connect-btn" @click="toBind"> 连接戒指 </view>
		<view class="to-bay" @click="toBuy"> 购买戒指 </view>
		<!-- 同步时间
    <view v-if="showSyncTime" class="last_update">
      <text v-if="isSeconds">已是最新数据</text>
      <text v-else>
        {{ lastUpdateDate ? "上次同步时间：" + lastUpdateDate : "" }}
      </text>
    </view>-->
		<view class="tip">
			请先将戒指与App连接
		</view>
		<view class="tip">
			您今天的状态不错,睡眠时间较昨日有所增长,压力指数也有所下降,建议可以进行适当运动,提升自己的体验.
		</view>
	</view>
</template>

<script>
	import store from "@/store/index.js";
	import dayjs from "dayjs";
	import {
		mapGetters
	} from "vuex";
	import {
		BLUETOOTH_STATUS,
		SEARCH_STATUS
	} from "@/store/BluetoothManager.js";
	import {
		getUserRing
	} from "@/utility/business.js";
	import {
		setWithExpiration,
		getWithExpiration
	} from "@/js_sdk/utils/expiration.js";
	import {
		bindUserRing,
		setRingMacAndName
	} from "@/api/ring/bind.js";
	import * as echarts from 'echarts';

	const systemInfo = uni.getSystemInfoSync();

	export default {
		props: {
			pageLoading: {
				type: Boolean,
				default: false,
			},
		},
		watch: {},
		data() {
			return {
				syncProgressVisible: false,
				progressTextArr: [],
				running: false,
				healthScore: 79
			};
		},
		computed: {
			...mapGetters("bleManage", ["deviceList", "searchStatus", "bluetoothState", "linkComplete", "getAvailable",
				"getPage", "autoLink"
			]),
			...mapGetters("ringDataManage", ["ring", "getSyncProgress", "getSyncLoading"]),

			isLogin() {
				return store.state.userToken;
			},

			isSeconds() {
				return "";
			},

			lastUpdateDate() {
				const ringUser = store.state.ringUser;
				if (!ringUser.lastUpDateTime) {
					return;
				}
				const last = dayjs(ringUser.lastUpDateTime);
				const interval = dayjs().diff(last, "seconds");

				if (interval < 60) {
					return `${interval}秒前`;
				} else if (interval < 3600) {
					// 60秒 <= interval < 1小时
					const minutes = Math.floor(interval / 60);
					return `${minutes}分钟前`;
				} else if (interval < 86400) {
					// 1小时 <= interval < 24小时
					const hours = Math.floor(interval / 3600);
					return `${hours}小时前`;
				} else if (interval < 604800) {
					// 24小时 <= interval < 7天
					const days = Math.floor(interval / 86400);
					return `${days}天前`;
				} else {
					// 7天 <= interval
					return last.format("YYYY.MM.DD HH:mm"); // 格式化为 YYYY.MM.DD HH:mm
				}
			},

			authCheckInterrupt() {
				return this.$store.state.bleManage.authCheckInterrupt;
			},

			isConnect() {
				return this.bluetoothState === BLUETOOTH_STATUS.CONNECTED;
			},

			isSearchingOrConnecting() {
				return this.bluetoothState === BLUETOOTH_STATUS.CONNECTING || this.searchStatus === SEARCH_STATUS
					.SEARCHING;
			},

			progress() {
				return Math.round(this.getSyncProgress);
			},

			ringName() {
				const {
					name,
					mac,
					customName
				} = store.state.ringDataManage.ring;
				return customName || name || mac;
			},

			ringMac() {
				const {
					mac,
					name,
					customName,
					ringType
				} = store.state.ringDataManage.ring;
				if (systemInfo.platform === "ios") {
					return ringType === 3 ? customName || name : name;
				}
				return mac;
			},

			canResearch() {
				return !this.isConnect && this.searchStatus === SEARCH_STATUS.NOTFOUND;
			},

			canReConnect() {
				return this.bluetoothState === BLUETOOTH_STATUS.DISCONNECTED || this.bluetoothState === BLUETOOTH_STATUS
					.TIMEOUT;
			},

			hasMac() {
				return store.hasBindRing;
			},

			notBindRing() {
				return !this.ringMac;
			},

			canSyncData() {
				return this.isConnect && !this.getSyncLoading && this.linkComplete;
			},

			showSyncProgress() {
				return this.getSyncLoading;
			},

			showSyncTime() {
				return this.isLogin;
			},

			specifyDevice() {
				return this.deviceList[0];
			},

			specifyDeviceAndSearchStatus() {
				return {
					device: this.specifyDevice,
					searchStatus: this.searchStatus,
				};
			},

			canAutoLink() {
				return this.autoLink && this.getAvailable;
			},
		},

		watch: {
			specifyDeviceAndSearchStatus: {
				handler({
					device,
					searchStatus
				}) {
					const isMain = this.getPage === "main";
					if (isMain && device && searchStatus === SEARCH_STATUS.FOUND && this.bluetoothState ===
						BLUETOOTH_STATUS.SEARCH) {
						this.$store.dispatch("bleManage/connectDevice", device);
					}
				},
				deep: true,
			},

			linkComplete(nv) {
				if (nv) {
					setWithExpiration("device", this.$store.state.bleManage.connectedDevice, 360);

					const devName = this.$store.state.bleManage.connectedDevice.name;
					const ringName = this.$store.state.ringDataManage.ring.name;
					const customName = this.$store.state.ringDataManage.ring.customName;

					if (devName !== ringName && devName !== customName) {
						setRingMacAndName({
							customName: devName,
						});
					}

					this.$nextTick(() => {
						setTimeout(() => {
							this.$store.dispatch("ringDataManage/syncData");
						}, 1000);
					});
				} else {
					this.$store.dispatch("ringDataManage/stopSyncData");
				}
			},

			canAutoLink: {
				handler(nv) {
					if (!nv.length) return;
					const isMain = this.getPage === "main";
					const available = nv.slice(-1)[0];
					if (isMain && available) {
						// 开启蓝牙
						this.toUserRing();
					} else {
						this.$store.dispatch("ringDataManage/stopSyncData");
					}
				},
				deep: true,
			},

			progress() {
				this.drawChart();
			},
		},

		async mounted() {

			console.log('尝试绘制进度条...'); // 添加日志确认
			this.drawChart();

			try {
				await this.$store.dispatch("bleManage/closeBluetooth");
				await this.$store.dispatch("bleManage/initBluetooth");
			} catch (error) {
				console.log("closeBluetooth or initBluetooth error", error);
			} finally {
				if (!this.authCheckInterrupt) {
					this.toUserRing();
				}
			}

		},

		methods: {
			drawChart() {
				// 使用ref获取canvas元素
				const canvasRef = this.$refs.healthChart;
				if (!canvasRef) {
					console.error('无法获取canvas元素');
					return;
				}

				// 使用uni.createCanvasContext获取上下文
				const ctx = uni.createCanvasContext('healthProgressChart', this);
				if (!ctx) {
					console.error('无法创建canvas上下文');
					return;
				}

				const width = 200; // 画布宽度
				const height = 200; // 画布高度
				const radius = 80; // 进度条半径
				const centerX = width / 2;
				const centerY = height / 2;
				const lineWidth = 20; // 进度条宽度

				console.log('开始绘制进度条，isConnect:', this.isConnect); // 添加日志确认

				// 清除画布
				ctx.clearRect(0, 0, width, height);

				// 绘制灰色背景圆环
				ctx.beginPath();
				ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
				ctx.setStrokeStyle("#ccc");
				ctx.setLineWidth(lineWidth);
				ctx.setLineCap("round");
				ctx.stroke();

				if (this.isConnect) {
					// 绘制橙色进度条
					const startAngle = -Math.PI / 2;
					const endAngle = startAngle + (this.healthScore / 100) * 2 * Math.PI;
					ctx.beginPath();
					ctx.arc(centerX, centerY, radius, startAngle, endAngle);
					ctx.setStrokeStyle("#FFA500");
					ctx.setLineWidth(lineWidth);
					ctx.setLineCap("round");
					ctx.stroke();
				}

				// 确保绘制操作执行
				ctx.draw();
			},

			async toUserRing() {
				const ring = await getUserRing();
				if (ring) {
					if (this.isConnect || this.isSearchingOrConnecting) {
						return;
					}
					this.toConnect();
				}
			},

			toLogin() {
				uni.navigateTo({
					url: "/pages/user/login",
				});
			},
			toBind() {
				uni.navigateTo({
					url: "/pages/ring/connect",
				});
			},
			toBuy() {
				return uni.showToast({
					title: "敬请期待",
					icon: "none",
				});
			},
			async toConnect() {
				if ([BLUETOOTH_STATUS.UNINITIALIZED, BLUETOOTH_STATUS.INITFAILED].includes(this.bluetoothState)) {
					await this.$store.dispatch("bleManage/initBluetooth");
				} else {
					await this.$store.dispatch("bleManage/closeBluetooth");
					await this.$store.dispatch("bleManage/initBluetooth");
				}
				const device = getWithExpiration("device");
				if (device && device.mac === this.ringMac) {
					this.$store.dispatch("bleManage/connectDevice", device);
				} else {
					this.$store.dispatch("bleManage/searchSpecifyRingDevice", this.ringMac);
				}
			},
			async research() {
				try {
					await this.$store.dispatch("bleManage/closeBluetooth");
					await this.$store.dispatch("bleManage/initBluetooth");
				} catch (error) {
					console.log("research error", error);
				} finally {
					this.$store.dispatch("bleManage/searchSpecifyRingDevice", this.ringMac);
				}
			},
			reconnect() {
				this.toConnect();
			},
			toSync() {
				const ringUser = store.state.ringUser;
				if (ringUser.lastUpDateTime) {
					const last = dayjs(ringUser.lastUpDateTime);
					const interval = dayjs().diff(last, "seconds");
					if (interval <= 30)
						return uni.showToast({
							title: "同步频繁，请稍候",
							icon: "none",
						});
				}

				if (!this.linkComplete) {
					return uni.showToast({
						title: "请等待",
						icon: "none",
					});
				}

				this.$nextTick(() => {
					this.$store.dispatch("ringDataManage/syncData");
					this.$emit("onSync");
				});
			},

			disconnect() {
				this.$store.dispatch("bleManage/disConnectDevice");
			},
		},
	};
</script>

<style lang="scss" scoped>
	.head_main {
		width: 100%;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		text-align: center;

		.progress-container {
			position: relative;
			margin-bottom: 20px;
		}

		.health-progress-chart {
			width: 200px;
			height: 200px;
		}

		.score-container {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			text-align: center;
			width: 100%;
		}

		.health-score {
			font-size: 36px;
			font-weight: 500;
			margin-bottom: 4px;
		}

		.no-data-tip {
			font-size: 14px;
			color: #999;
			display: block;
			width: 100%;
			text-align: center;
			margin-top: 4px;
		}

		.connect-btn {
			width: 500rpx;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 20rpx;
			background: rgba(25, 82, 248, 1);
			margin: auto;
			margin-bottom: 22rpx;

		}

		.to-bay {
			color: rgba(35, 89, 248, 1);
			font-size: 24rpx;
			text-align: center;
			margin-bottom: 60rpx;
		}

		.tip {
			padding-left: 32rpx;
			font-size: 24rpx;
			color: rgba(153, 153, 153, 1);
			margin-bottom: 20rpx;
			text-align: left;
			width: 100%;
		}

		.ring_name {
			color: black;
			text-align: center;
			font-family: PingFang SC;
			font-size: 36rpx;
			font-weight: 500;
			line-height: 50rpx;
			margin-bottom: 20rpx;
		}

		.last_update {
			font-size: 20rpx;
			font-weight: 400;
			line-height: 28rpx;
			text-align: center;
			color: rgba($color: #000000, $alpha: 0.8);
			margin-top: 12rpx;
		}
	}
</style>